package com.zyf.mvc.controller;

import com.zyf.mvc.pojo.ZyfMenu;
import com.zyf.mvc.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * Created by a on 2017/5/15.
 */
@Controller
@RequestMapping(value = "/base")
public class BaseController {

     @Autowired
    private BaseService baseservice;
    @RequestMapping(value = "/")
    @ResponseBody
    public List<ZyfMenu> base_menu() throws Exception {

        List<ZyfMenu> newmenu = new ArrayList<ZyfMenu>();
        List<ZyfMenu> rootmenu = new ArrayList<ZyfMenu>();
        newmenu = baseservice.selectByExample();
        for (ZyfMenu menu: newmenu){

            if ("".equals(menu.getParentid())||menu.getParentid()==null){
                rootmenu.add(menu);
            }}
            for (ZyfMenu menu1: rootmenu){

                menu1.setChildmenu(getCliden(newmenu,menu1.getId()));
            }
        for (ZyfMenu menu1 : rootmenu) {
            System.out.print(menu1);
        }

        //适配bui动态导航条的数据格式
        List list  = new ArrayList();
        for(ZyfMenu test : rootmenu) {
            List list2  = new ArrayList();
            Map map = new HashMap();
            Map map4 = new HashMap();
            map.put("id",test.getId());
            map4.put("title","11");
            if (test.getChildmenu()!=null){
            for (ZyfMenu test2: test.getChildmenu()) {
            Map map2 = new HashMap();
             map2.put("id",test2.getId());
                map2.put("text",test2.getName());
                map2.put("href",test2.getUrl());
            list2.add(map2);

            }
               Map map3 =  (Map) list2.get(0);
               map.put(" homePage",map3.get("id"));

        }
            map.put("items","1");
        }




        return rootmenu;
    }
    public  List<ZyfMenu> getCliden(List<ZyfMenu> menu ,int id){
        List<ZyfMenu> childmenu =new ArrayList<ZyfMenu>();
        for(ZyfMenu menu1:menu){
           if(menu1.getParentid()!=null) {
               if (menu1.getParentid() == id) {
                   childmenu.add(menu1);
               }
           }
        }
        for (ZyfMenu menu2 : childmenu) {// 没有url子菜单还有子菜单
            if (menu2.getUrl()==null||"".equals(menu2.getUrl())) {
                // 递归
                menu2.setChildmenu(getCliden( menu,menu2.getId()));
            }
        } // 递归退出条件
        if (childmenu.size() == 0) {
            return null;
        }
        return childmenu;
    }






}
